<?php

namespace Admin\Model;

use Zend\Db\TableGateway\AbstractTableGateway;
use Zend\Db\Adapter\Adapter;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\Sql\Select;


class HocsinhTable extends AbstractTableGateway {

    protected $table = 'hocsinh';

    public function __construct(Adapter $adapter) {
        $this->adapter = $adapter;
        $this->resultSetPrototype = new ResultSet();
        $this->resultSetPrototype->setArrayObjectPrototype(new Hocsinh());

        $this->initialize();
    }

    public function fetchAll(Select $select = null) {
        if (null === $select)
            $select = new Select();
        $select->from($this->table,array('*'))
				->join(
					'lop',
					'lop.id = hocsinh.lop',
					array('tenlop'));
        $resultSet = $this->selectWith($select);
        $resultSet->buffer();
        return $resultSet;
    }

    public function getHocsinh($id) {
        $id = (int) $id;
        $rowset = $this->select(array('id' => $id));
        $row = $rowset->current(); 
        return $row;
    }

    public function saveHocsinh(Hocsinh $hocsinh) {
		
			
		
        

        $id = (int) $hocsinh->id;
        if ($id == 0) {
			$data = array(
				'mahs' => $hocsinh->mahs,
				'tenhs' => $hocsinh->tenhs,
				'ngaysinh' => $hocsinh->ngaysinh,
				'gioitinh' => $hocsinh->gioitinh,
				'lop' => $hocsinh->lop,
			);
            	
                $this->insert($data);
            
        } else {
			
			$data = array(
				'mahs' => $hocsinh->mahs,
				'ngaysinh' => $hocsinh->ngaysinh,
				'tenhs' => $hocsinh->tenhs,
				'gioitinh' => $hocsinh->gioitinh,
				'lop' => $hocsinh->lop,
			);
            if ($this->getHocsinh($id)) {
				
					$this->update($data, array('id' => $id));
				
            } else {
                throw new \Exception('Không tồn tại');
            }
        }
    }

    public function deleteHocsinh($id) {
        $this->delete(array('id' => $id));
    }
	public function xoaHocsinh($id) {
		
        $this->delete('id IN (' . $id . ')');
    }
	
	//kiem tra ton tai
	public function check_exists($mahs,$id)
	{
		//$rowset = $this->select(array('title' => $title));
        //$row = $rowset->current();
		$resultSet = $this->select(array('mahs = "'.$mahs.'"', 'id != "'.$id.'"'));
    	$row = $resultSet->current();
        return $row;
		
	}
	


}
